// pages/statisticians/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    allObj: {},
    active: ['0'],
    activeNames: [],
    allMoneyData: {},
    expenditureObj: {},
    borrowingObj: {},
    accountObj: {},
    changeObj: {},
    collectionObj: {},
    expenditureData: [],
    borrowingData: [],
    accountData: [],
    changeData: [],
    collectionData: [],
    classifyList: [],
    classifyList1: [],
    classifyList2: [],
    classifyList3: [],
    classifyList4: [],
    classifyList5: [],
    admin: 0,
    expenditureChecked: false,
    borrowingChecked: false,
    accountChecked: false,
    changeChecked: false,
    collectionChecked: false,
    expenditureIds: '',
    borrowingIds: '',
    accountIds: '',
    changeIds: '',
    collectionIds: '',
    share: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ share: options?.share })
    this.setPermissions();
    this.getAllStatisticians();
    this.getExpenditure();
    this.getBorrowing();
    this.getAccount();
    this.getChange();
    this.getCollection();
    this.getList();
    this.getList(1);
    this.getList(2);
    this.getList(3);
    this.getList(4);
    this.getList(5);
    this.getAllMoney();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({ admin: wx.getStorageSync('admin') });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `财务统计`,
      path: `/pages/statisticians/index?share=true`
    }
  },

  getAllStatisticians() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selTotal`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const obj = res.data.data;
          obj.saleTatal = parseFloat(obj.changeTotal) + parseFloat(obj.total);
          obj.balanceTotal = (parseFloat(obj.total) + parseFloat(obj.changeTotal) - parseFloat(obj.collectionTotal)).toFixed(2);
          this.setData({ allObj: obj });
        } else {
          wx.showToast({
            title: res.data.msg || '出错啦！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  getAllMoney() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selFinanceTotal?financeId=0`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const obj = res.data.data;
          this.setData({ allMoneyData: obj });
        }
      }
    })
  },

  activeChange(e) {
    this.setData({ active: e.detail })
  },

  collapseChange(e) {
    this.setData({ activeNames: e.detail.slice(-1) })
  },

  getExpenditure(e) {
    wx.showLoading();
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selExpenditureList`,
      method: "GET",
      data: { ...this.data.expenditureObj },
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          if (e) this.getAllStatisticians();
          let dataMoney = 0;
          res.data.rows.forEach((item, index) => {
            item.index = res.data.rows?.length - index;
            if(this.data.changeObj.isDisable === 0 && item.isDisable == 0) {
              dataMoney += parseFloat(item.money);
            }else if(item.isDisable == 1){
              dataMoney += parseFloat(item.money);
            }
          });
          this.setData({ expenditureData: res.data.rows, expenditureTotal: res.data.total, expenditureMoney: dataMoney.toFixed(2), expenditureChecked: false });
        }
      }
    })
  },
  getBorrowing(e) {
    wx.showLoading();
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selBorrowingList`,
      method: "GET",
      data: { ...this.data.borrowingObj },
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          if (e) this.getAllStatisticians();
          let dataMoney = 0;
          res.data.rows.forEach((item, index) => {
            item.index = res.data.rows?.length - index;
            if(this.data.changeObj.isDisable === 0 && item.isDisable == 0) {
              dataMoney += parseFloat(item.money);
            }else if(item.isDisable == 1){
              dataMoney += parseFloat(item.money);
            }
          });
          this.setData({ borrowingData: res.data.rows, borrowingTotal: res.data.total, borrowingMoney: dataMoney.toFixed(2), borrowingChecked: false });
        }
      }
    })
  },
  getAccount(e) {
    wx.showLoading();
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selAccountList`,
      method: "GET",
      data: { ...this.data.accountObj },
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          if (e) this.getAllStatisticians();
          let dataMoney = 0;
          res.data.rows.forEach((item, index) => {
            item.index = res.data.rows?.length - index;
            if(this.data.changeObj.isDisable === 0 && item.isDisable == 0) {
              dataMoney += parseFloat(item.money);
            }else if(item.isDisable == 1){
              dataMoney += parseFloat(item.money);
            }
          });
          this.setData({ accountData: res.data.rows, accountTotal: res.data.total, accountMoney: dataMoney.toFixed(2), accountChecked: false });
        }
      }
    })
  },
  getChange(e) {
    wx.showLoading();
    console.log(this.data.changeObj)
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selChangeList?financeId=0`,
      method: "GET",
      data: { ...this.data.changeObj },
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          if (e) this.getAllMoney();
          let dataMoney = 0;
          res.data.rows.forEach((item, index) => {
            item.index = res.data.rows?.length - index;
            if(this.data.changeObj.isDisable === 0 && item.isDisable == 0) {
              dataMoney += parseFloat(item.money);
            }else if(item.isDisable == 1){
              dataMoney += parseFloat(item.money);
            }
          });
          this.setData({ changeData: res.data.rows, changeTotal: res.data.total, changeMoney: dataMoney.toFixed(2), changeChecked: false });
        }
      }
    })
  },
  getCollection(e) {
    wx.showLoading();
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/selCollectionList?financeId=0`,
      method: "GET",
      data: { ...this.data.collectionObj },
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          if (e) this.getAllMoney();
          let dataMoney = 0;
          res.data.rows.forEach((item, index) => {
            item.index = res.data.rows?.length - index;
            if(this.data.changeObj.isDisable === 0 && item.isDisable == 0) {
              dataMoney += parseFloat(item.money);
            }else if(item.isDisable == 1){
              dataMoney += parseFloat(item.money);
            }
          });
          this.setData({ collectionData: res.data.rows, collectionTotal: res.data.total, collectionMoney: dataMoney.toFixed(2), collectionChecked: false });
        }
      }
    })
  },
  getList(status) {
    wx.showLoading();
    let url = `${app.globalData.baseUrl}/api/classify/selDictData`;
    if (status) url = `${app.globalData.baseUrl}/api/classify/selDictData?status=${status}`
    wx.request({
      url: url,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code == 0) {
          switch (status) {
            case 1:
              this.setData({ classifyList1: res.data.data });
              break;
            case 2:
              this.setData({ classifyList2: res.data.data });
              break;
            case 3:
              this.setData({ classifyList3: res.data.data });
              break;
            case 4:
              this.setData({ classifyList4: res.data.data });
              break;
            case 5:
              this.setData({ classifyList5: res.data.data });
              break;
            default:
              this.setData({ classifyList: res.data.data });
          }

        } else {
          wx.showToast({
            title: res.data.msg || '出错啦！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  onSearch1(e) {
    this.setData({ expenditureObj: e.detail });
    this.getExpenditure();
  },

  onExport1(e) {
    this.exportData(1, {...this.data.expenditureObj, ids: this.data.expenditureIds});
  },

  onSearch2(e) {
    this.setData({ borrowingObj: e.detail })
    this.getBorrowing();
  },

  onExport2(e) {
    this.exportData(2, {...this.data.borrowingObj, ids: this.data.borrowingIds});
  },

  onSearch3(e) {
    this.setData({ accountObj: e.detail })
    this.getAccount();
  },

  onExport3(e) {
    this.exportData(3, {...this.data.accountObj, ids: this.data.accountIds});
  },

  onSearch4(e) {
    this.setData({ changeObj: e.detail })
    this.getChange();
  },

  onExport4(e) {
    this.exportData(4, {...this.data.changeObj, ids: this.data.changeIds});
  },

  onSearch5(e) {
    this.setData({ collectionObj: e.detail })
    this.getCollection();
  },

  onExport5(e) {
    this.exportData(5, {...this.data.collectionObj, ids: this.data.collectionIds});
  },

  onAllChangeChange(e) {
    this.setData({
      changeChecked: e.detail.allChecked,
      changeData: e.detail.list,
      changeIds: e.detail.ids?.join(','),
    });
  },

  onAllCollectionChange(e) {
    this.setData({
      collectionChecked: e.detail.allChecked,
      collectionData: e.detail.list,
      collectionIds: e.detail.ids?.join(','),
    });
  },

  onAllExpenditureChange(e) {
    this.setData({
      expenditureChecked: e.detail.allChecked,
      expenditureData: e.detail.list,
      expenditureIds: e.detail.ids?.join(','),
    });
  },

  onAllBorrowingChange(e) {
    this.setData({
      borrowingChecked: e.detail.allChecked,
      borrowingData: e.detail.list,
      borrowingIds: e.detail.ids?.join(','),
    });
  },

  onAllAccountChange(e) {
    this.setData({
      accountChecked: e.detail.allChecked,
      accountData: e.detail.list,
      accountIds: e.detail.ids?.join(','),
    });
  },

  exportData(type, data) {
    wx.showLoading({
      title: '导出中...',
    });
    let url = '';
    if(type === 1) url = 'selExpenditureListExport';
    if(type === 2) url = 'selBorrowingListExport';
    if(type === 3) url = 'selAccountListExport';
    if(type === 4) url = 'selChangeListExport?financeId=0';
    if(type === 5) url = 'selCollectionListExport?financeId=0';
    const that = this;
    wx.request({
      url: `${app.globalData.baseUrl}/api/classify/${url}`,
      method: "POST",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data,
      success: (res) => {
        if(res.data.code == 0) {
          const url = `${app.globalData.baseUrl}/common/download?fileName=${encodeURI(res.data.msg)}`;
          wx.getSystemInfo({
            success: function(result) {
              if (result.platform === 'ios' || result.platform === 'android') {
                that.saveMobile(url);
              } else if (result.platform === 'windows' || result.platform === 'mac') {
                that.savePc(url);
              }
            }
          });
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '出错啦',
        })
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },
  
  savePc(url) {
    wx.request({
      url: url,
      responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制数据
      success: (res) => {
        // 获取文件名
        const fileName = url.split('=').pop();
     
        // 写入文件
        wx.getFileSystemManager().writeFile({
          filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 指定要写入的文件路径
          data: res.data, // 文件内容
          encoding: 'binary', // 指定文件编码
          success: (writeRes) => {
            console.log('文件保存成功', writeRes);
            // 这里可以调用wx.saveFileToDisk将文件保存到用户电脑
            wx.saveFileToDisk({
              filePath: wx.env.USER_DATA_PATH + '/' + fileName,
              success: (saveRes) => {
                console.log('文件保存到电脑成功', saveRes);
              },
              fail: (error) => {
                console.error('文件保存到电脑失败', error);
              }
            });
          },
          fail: (error) => {
            console.error('文件保存失败', error);
          }
        });
      },
      fail: (error) => {
        console.error('文件下载失败', error);
      }
    });
  },

  saveMobile(url) {
    console.log(url, 'mobile')
    wx.downloadFile({
      url,
      success(res) {
        if (res.statusCode === 200) {
          console.log(res.tempFilePath)
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true,
            fileType: "xlsx"
          });
        }
      }
    })
  },
  setPermissions() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getUserDept`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const deptIds = [];
          res?.data?.data?.forEach(item => {
            deptIds.push(item.deptId);
          });
          if (deptIds.length === 0 && (wx.getStorageSync('admin') == 0 || !wx.getStorageSync('admin'))) {
            wx.switchTab({
              url: '/pages/index/index',
            });
            return;
          }
        }
      }
    })
  },
})